<?php

namespace control;
/*
*钢瓶收发明细表
*/
class steelCylinderClass extends adIndexClass
{
    private const page = 'steelCylinder'; # 权限
    private const table = 'steel_cylinder_receive_log'; # 数据表
    private const title = '钢瓶收发明细表';
    private const stateOption = ['草稿', '在库', '已发货'];
    private const vc_node_data = [
        'NONE'=>'无',
        'FULL_IN'=>'已满瓶入库',
        'FULL_OUT'=>'已满瓶出库',
        'EMPTY_IN'=>'已空瓶入库',
        'EMPTY_OUT'=>'已空瓶出库',
        'EMPTY_RET'=>'已空瓶回收',
        'ADD_BEFORECHECK'=>'已充前检查',
        'ADD'=>'已充气',
        'ADD_AFTERCHECK'=>'已充后复检',
        'TO'=>'已送达',
        'CAR'=>'已装车'
    ];
    private const tableKehu        = 'kehu';

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'barcode' => [
                'name'  => '内部编码',
                'width' => 200,
                'sort' => 1,
            ],
            'code' => [
                'name'  => '出厂码',
                'width' => 200,
                'sort' => 1,
            ],
            'model'  => [
                'name'  => '规格型号',
                'width' => 200,
            ],
            'vc_node'         => [
                'name'  => '流转节点',
                'width' => 200,
            ],
            'vc_customer'         => [
                'name'  => '客户',
                'width' => 200,
            ],
            'vc_username_ry'          => [
                'name'  => '操作人员',
                'width' => 200,
            ],
            'dt_date'          => [
                'name'  => '操作时间',
                'width' => 150,
            ],
        ];
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '内部编码'   => text(array("name" => "barcode")),
                    '出厂码'   => text(array("name" => "code")),
                    '规格型号'  => text(array("name" => "model")),
                ],
                [
                    "日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*钢瓶收发明细入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        $button .= "<span class='spanButton' onclick=\"batchPutInStock('" . self::page . "','addData','homeSearchForm')\">获取最新数据</span>\n";
        $button .= "
					<script>
                        function batchPutInStock(page,fun,name) {
                            let dataTemp = $('form[name=\"'+name+'\"]').serialize();
                            layer(page,fun,dataTemp)
                        }
                    </script>
				";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*钢瓶收发明细列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'orderNo' => $this->post('orderNo'),
            'khid' => $this->post('khid'),
            'state' => $this->post('state'),
            'coid'=>self::$coid,
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
        ]);
        $and = "";
        if ($this->post('time')) {
            $time = explode('~', $this->post('time'));
            $and = " and steelCylinderId in (SELECT id FROM steel_cylinder WHERE 1=1 and (jsonData->'$.DT_ADD_END' BETWEEN  '{$time[0]}' and '{$time[1]}'))";
        }
        if($this->post('model')){
            $and = " and steelCylinderId in (SELECT id FROM steel_cylinder WHERE model like '%".$this->post('model')."%')  ";
        }
        if($this->post('code')){
            $and = " and steelCylinderId in (SELECT id FROM steel_cylinder WHERE code like '%".$this->post('code')."%')  ";
        }
        if($this->post('barcode')){
            $and = " and steelCylinderId in (SELECT id FROM steel_cylinder WHERE barcode like '%".$this->post('barcode')."%')  ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where.$and, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            $field = query("steel_cylinder","id='".$array['steelCylinderId']."'");
            //列表控件
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['id']],
            ];
            $liButton[] = $this->dominate($dominate) . hidden(["name" => "cylinderId", "value" => $array['id']]);
            $jsonData = json_decode($array['jsonData'],true);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "barcode":
                        $row[] =  $field['barcode'];
                        break;
                    case "code":
                        $row[] =  $field['code'];
                        break;
                    case "model":
                        $row[] =  $field['model'];
                        break;
                    case "vc_node":
                        $row[] =  self::vc_node_data[$jsonData['VC_NODE']];
                        break;
                    case "vc_customer":
                        $row[] =  $jsonData['VC_CUSTOMER'];
                        break;
                    case "vc_username_ry":
                        $row[] =  $jsonData['VC_USERNAME_RY'];
                        break;
                    case "dt_date":
                        $row[] =  $jsonData['DT_DATE'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' =>  $where.$and,
            'field'  => "count(*) as dt_date",
        ]);
        $total    = [
            'dt_date'        => $totalQuery['dt_date'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] .clear;
        return json_encode($json, 320);
    }

    /**
     * 获取最新钢瓶信息
     * @return bool|string
     */
    public function addData(): bool|string
    {
        if($this->post('time')){
            $time = explode('~', $this->post('time'));
            $startDate = date("Y-m-d",strtotime($time[0]));
        }else{
            $startDate = date("Y-m-d");
        }
        $tags = find(['table' =>'steel_cylinder','where'=>'1=1 AND barcode IS NOT NULL']);
        if(empty($tags['array'])){
            $json['warn'] = "获取内部编码失败";
            goto resp;
        }
        $tags = array_column($tags['array'],'barcode');
        $tags = array_unique($tags);
        //跨域需提交的数据
        $tokenData = $this->getToken();
        if(!$tokenData['code']){
            $json['warn'] = $tokenData['msg'];
            goto resp;
        }
        $steelCylinder = $this->send_post("txhg/qp_filldata",['tags'=>implode(',',$tags),'startDate'=>$startDate],$tokenData['data']);//获取数据
        if($steelCylinder['code'] !== '1'){
            $json['warn'] = "获取数据失败；失败原因：".$steelCylinder['msg'];
            goto resp;
        }
        $this->startTrans();

        $json['warn'] = "更新成功";
        foreach ($steelCylinder['data'] as $item){
            //保存钢瓶信息
            $field = query("steel_cylinder","barcode='".$item['qpInfo']['VC_TAGNO']."'");
            if(!$field['id']){
                continue;
            }
            $VC_USECUST = $item['qpInfo']['VC_USECUST'];
            $kehu = query('kehu',"companyName = '$VC_USECUST'");
            $data = [
                'endTime' => $item['qpInfo']['DT_NEXTCHECK'],
                'updateTime' => $this->time,
                'jsonData' => json_encode($item['qpInfo']),
            ];
            if($kehu['khid']){
                $data['khid'] = $kehu['khid'];
            }
            $warn = static::update([
                'table' => 'steel_cylinder',
                'field' => $data,
                'where' => " id = '$field[id]'"
            ]);
            if(!in_array($warn, ["新增成功", "更新成功"])){
                $json['warn'] = "保存钢瓶基础信息失败；失败原因：".$warn;
                $this->rollback();
                goto resp;
            }
            //保存钢瓶记录信息
            foreach ($item['fillList'] as $fill) {
                $detail = query("steel_cylinder_detail","steelCylinderId='".$field['id']."' and log_time <= '$fill[DT_ADD_END]'");
                if(!empty($detail['id'])){
                    $data = [
                        'log_time' => $fill['DT_ADD_END'] ?: '',
                        'updateTime' => $this->time,
                        'jsonData' => json_encode($fill),
                    ];
                    $warn = static::update([
                        'table' => 'steel_cylinder_detail',
                        'field' => $data,
                        'where' => " id = '$detail[id]'"
                    ]);
                }else{
                    $data = [
                        'id' => self::getId(),
                        'coid' => self::$coid,
                        'steelCylinderId' => $field['id'],
                        'text' => '',
                        'updateTime' => $this->time,
                        'jsonData' => json_encode($fill),
                        'time' => $this->time,
                        'log_time' => $fill['DT_ADD_END'] ?: '',
                    ];
                    $warn = static::insert([
                        'table' => 'steel_cylinder_detail',
                        'field' => $data
                    ]);
                }
                if(!in_array($warn, ["新增成功", "更新成功"])){
                    $json['warn'] = "保存钢瓶充装信息失败；失败原因：".$warn;
                    $this->rollback();
                    goto resp;
                }
            }
            //保存流转记录
            foreach ($item['tracks'] as $val_data) {
                $detail_log = query("steel_cylinder_receive_log","steelCylinderId='".$field['id']."' and dt_time == '$val_data[DT_DATE]'");
                if(!empty($detail_log['id'])){
                    $data = [
                        'dt_time' => $val_data['DT_DATE'] ?: '',
                        'steelCylinderId' => $field['id'],
                        'updateTime' => $this->time,
                        'jsonData' => json_encode($val_data),
                    ];
                    $warn = static::update([
                        'table' => 'steel_cylinder_receive_log',
                        'field' => $data,
                        'where' => " id = '$detail_log[id]'"
                    ]);
                }else{
                    $data = [
                        'id' => self::getId(),
                        'coid' => self::$coid,
                        'updateTime' => $this->time,
                        'steelCylinderId' => $field['id'],
                        'jsonData' => json_encode($val_data,JSON_UNESCAPED_UNICODE),
                        'time' => $this->time,
                        'dt_time' => $val_data['DT_DATE'] ?: '',
                    ];
                    $warn = static::insert([
                        'table' => 'steel_cylinder_receive_log',
                        'field' => $data
                    ]);
                }
                if(!in_array($warn, ["新增成功", "更新成功"])){
                    $json['warn'] = "保存钢瓶流转信息失败；失败原因：".$warn;
                    $this->rollback();
                    goto resp;
                }
            }
        }
        $this->commitTrans();
        $json['msg'] = "获取并保存数据成功";
        $_SESSION['warn'] = $json['warn'];
        $json['warn']     = 2;
        $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => " coid='".self::$coid."' and id in ('".implode("','",$checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $field = query("steel_cylinder","id='".$array['steelCylinderId']."'");
                $jsonData = json_decode($array['jsonData'],true);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '内部编码'=>$field['barcode'],
                            '出厂码'=>$field['code'],
                            '规格型号'=>$field['model'],
                            '业务类型'=>$array['classify'],
                            '流转节点'=>self::vc_node_data[$jsonData['VC_NODE']],
                            '客户'=>$jsonData['VC_CUSTOMER'],
                            '操作人员'=>$jsonData['VC_USERNAME_RY'],
                            '操作时间'=>$jsonData['DT_DATE'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了钢瓶收发明细表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "钢瓶收发明细表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'内部编码',
                    'aliasName'=>'内部编码',//barcode
                ],
                [
                    'columnName'=>'出厂码',//code
                    'aliasName'=>'出厂码',
                ],
                [
                    'columnName'=>'规格型号',//model
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'流转节点',//vc_node
                    'aliasName'=>'流转节点',
                ],
                [
                    'columnName'=>'客户',//vc_customer
                    'aliasName'=>'客户',
                ],
                [
                    'columnName'=>'操作人员',//vc_username_ry
                    'aliasName'=>'操作人员',
                ],
                [
                    'columnName'=>'操作时间',//dt_date
                    'aliasName'=>'操作时间',
                ],
            ]
        };
    }

}